package com.sdgakj.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.Date;
import java.util.Random;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sdgakj.enums.EnumSMSType;
import com.sdgakj.service.ServiceException;

/**
 * @ClassName: SMSSender
 * @Description: TODO 发送 短信
 * @author henryfang1@163.com
 * @date 2012-9-9 下午03:51:34
 * 
 */

public class SMSSender {
	private static Logger logger = LoggerFactory.getLogger(SMSSender.class);

	// 发送传递的参数
	private static String USERNAME = "cf_guangan"; //cf_gagw
	private static String PASSWORD = "MumRzn"; //6nARDC
	private static String SENDURL = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";

	/**
	 * 创建一个新的实例 SMSSender. 助通科技提供的用户名与地址
	 */
	/****
	 * USERNAME 用户名（必填） PASSWORD 密码（必填） mobile 手机号，多个手机号为用半角 ,
	 * 分开，如13899999999,13688888888(最多100个，必填) content 发送内容（必填） dstime
	 * 定时时间，为空时表示立即发送（选填） productid 产品id(必填) XH 扩展号,留空
	 ***/

	/**
	 * 发送短信
	 * 
	 * @author zhaozhe
	 * @time 2015年10月18日
	 * @param mobile
	 *            手机号
	 * @param content
	 *            内容
	 * @param smsType
	 *            短信类型，通知/验证码
	 * @return
	 * @throws DocumentException 
	 */
	public static String sendSms(String mobile, String content, EnumSMSType smsType){
		// 一天内，同一手机号仅允许发送5条短信
		Object times = RedisClient
				.cacheGet(mobile.concat("_code_times_").concat(DateUtil.formatDateToString(new Date(), "yyyyMMdd")));
		if (times != null && Integer.valueOf(times.toString()) >= 20) {
			logger.info("单一号码短信条数超限------------->:" + mobile);
			throw new ServiceException("您今天已达验证码发送上限");
		}

		String sendUrl = "";
		// try {// 否则发到手机乱码
		sendUrl = SENDURL + "&account=" + USERNAME + "&password=" + PASSWORD + "&mobile=" + mobile + "&content="
				+ content;

		logger.info("短信内容为------------->:" + content);
		String result= "";
//		String result = getUrl(sendUrl);
		try{
		    result =sendMessage(mobile,content);
			logger.info("短信发送结果：" + result);	
			
			if (result != null && result.indexOf("<code>2") > 0) {  //判断返回码是否是2，2代表成功
//			if(code == "2"){
				times = times != null ? (Integer.valueOf(times.toString())) + 1 : 1;
				RedisClient.cacheAdd(
						mobile.concat("_code_times_").concat(DateUtil.formatDateToString(new Date(), "yyyyMMdd")),
						times.toString(), 60 * 60 * 24);
			}			
		}catch(Exception e){
			logger.error("tel:"+mobile+"发送失败,错误为"+e.getMessage());
		}

		return result;
	}
	
    private static String sendMessage(String mobile, String content) {
		 HttpClient client = new HttpClient(); 
		 PostMethod method = new PostMethod(SENDURL); 
		 
		client.getParams().setContentCharset("UTF-8");
		client.getHttpConnectionManager().getParams().setConnectionTimeout(20000);  
		client.getHttpConnectionManager().getParams().setSoTimeout(30000); 
		method.setRequestHeader("ContentType","application/x-www-form-urlencoded;charset=UTF-8");

		NameValuePair[] data = {//提交短信
			    new NameValuePair("account", USERNAME), 
			    new NameValuePair("password", PASSWORD), //密码可以使用明文密码或使用32位MD5加密
			    //new NameValuePair("password", util.StringUtil.MD5Encode("密码")),
			    new NameValuePair("mobile", mobile), 
			    new NameValuePair("content", content),
		};
		
		method.setRequestBody(data);
		String SubmitResult="";
		try {
			client.executeMethod(method);			
		    SubmitResult =method.getResponseBodyAsString();
//			System.out.println("send tel:"+mobile);
//			System.out.println(SubmitResult);
			logger.info("send tel:"+mobile);
		    logger.info(SubmitResult);
//			Document doc = DocumentHelper.parseText(SubmitResult); 
//			Element root = doc.getRootElement();
//
//
//			String code = root.elementText("code");	
//			String msg = root.elementText("msg");	
//			String smsid = root.elementText("smsid");	
//			
//			
//			System.out.println(code);
//			System.out.println(msg);
//			System.out.println(smsid);
//						
//			if(code == "2"){
//				System.out.println("短信提交成功");
//			}
			
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
		    method.releaseConnection();
			client.getHttpConnectionManager().closeIdleConnections(0);
		}
		return SubmitResult;
	}

	/**
	 * @Title: getUrl
	 * @Description: 获取地址
	 * @param urlString
	 * @return
	 */

	private static String getUrl(String urlString) {
		StringBuilder sb = new StringBuilder();
		BufferedReader reader = null;
		String result = "";
		try {
			URL url = new URL(urlString);
			URLConnection conn = url.openConnection();
			conn.setReadTimeout(30000);
			reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			for (String line = null; (line = reader.readLine()) != null;) {
				sb.append(line + "\n");
			}

			result = URLDecoder.decode(sb.toString(), "UTF-8");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		} finally {
			try {
				reader.close();
			} catch (Exception e) {
				logger.error(e.getMessage());
			}
		}

		return result;
	}
	
	
	public static String sendValidateCode(String mobile) throws DocumentException {
		
		Random random = new Random();
		String sRand = String.valueOf(random.nextInt(9000) + 1000);
		String content = "您的验证码是：" + sRand + "。请不要把验证码泄露给其他人。如非本人操作，可不用理会！（验证码半小时内有效）";
		RedisClient.cacheAdd(mobile.concat("_code"), sRand, 30 * 60);

		// 发送短信
		return SMSSender.sendSms(mobile, content, EnumSMSType.SECURITY_CODE);
	}

	/***
	 * 测试地址
	 * @throws DocumentException 
	 * 
	 ***/
	public static void main(String[] args) throws DocumentException {
		// 您的验证码是：8322。请不要把验证码泄露给其他人。如非本人操作，可不用理会！（半小时内有效）
		String message = "您的验证码是：" + 1231 + "。请不要把验证码泄露给其他人。如非本人操作，可不用理会！（半小时内有效）";
		String phone = "18730631747";// ,13581687920
		String r = SMSSender.sendSms(phone, message, EnumSMSType.SECURITY_CODE);
		System.out.println("-- SMS service return code :" + r);
	}
}